<?php

namespace App\Http\Controllers\Home;
use DB;
use Illuminate\Http\Request;
use App\Http\Requests\HomeRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    //显示登录页面
	public function login(){
		return view('home.login');
	}

	//执行登录
	public function doLogin(Request $request){
		// dd($request->all());
		// 根据用户名查询用户
    	$user = DB::table('user')->where('phone',$request->input('phone'))->first();
    	// dd($user);
    	if(empty($user)){
    		return back()->with('error','手机号不正确');
    	}

    	if($request->input('password') != $user->password){
    		return back()->with('error','密码不正确');
    	}

 		//检测验证码是否正确
    	$v = $request->input('vcode');
    	// dd($v);
    	$vcode = $request->session()->get('Vcode');
        // dd($vcode);
        if($v == $vcode){
        	session(['id'=>$user->id]);
   			return redirect('/admin')->with('success','欢迎'.$user->username.'登录');
        }else{
        	return back()->with('error','验证码不正确');
        }

	}

	//验证码
    public function vcode(){
    	// echo '222';
    	 ob_clean();//清除输出缓存区的内容
	    //生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();

        //把内容存入session
        session(['Vcode'=>$phrase]);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();

       //看到图片输出 需要die
    }
}
